//
//  CZNetworkTool.m
//  i0S007通用项目
//
//  Created by Apple on 16/2/21.
//  Copyright © 2016年 Apple. All rights reserved.
//

#import "CZNetworkTool.h"

@implementation CZNetworkTool

static CZNetworkTool *instance = nil;
+ (instancetype)sharedInstance {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        NSURL *url = [NSURL URLWithString:@"http://apicloud.mob.com/"];
        instance = [[self alloc] initWithBaseURL:url];
        
        // mob返回的网络数据是:text/html类型,AFN默认不支持,我们添加
        // 1.获取已经支持的类型
        NSMutableSet *acceptableContentTypes = [NSMutableSet setWithSet:instance.responseSerializer.acceptableContentTypes];
        
        // 2.添加需要支持的类型
        [acceptableContentTypes addObject:@"text/html"];
        
        // 3.在将添加好的支持类型赋值给AFN
        instance.responseSerializer.acceptableContentTypes = acceptableContentTypes;
        
    });
    
    return instance;
}

+ (instancetype)allocWithZone:(struct _NSZone *)zone {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [super allocWithZone:zone];
    });
    
    return instance;
}

- (id)copyWithZone:(NSZone *)zone {
    return instance;
}

// 获取某个城市的天气数据
- (void)queryWeatherWithProvince:(NSString *)province city:(NSString *)city finished: (void(^)(NSDictionary *responseObject, NSError *error))finished {
    // 3.url
    NSString *url = @"v1/weather/query";
    
    // 4.请求参数
    NSDictionary *parameter = @{@"key": MobWeatherAppKey,
                                @"city": city,
                                @"province": province};
    
    // 5.发送请求
    [self GET:url parameters:parameter progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        // 网络请求只负责获取数据.数据的处理,不关心
        // 6.通过block将获取到的网络数据返回给调用的对象
        finished(responseObject, nil);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        finished(nil, error);
    }];
}
@end
